/**
 * Created by Dalyn on 2017/2/28.
 * 采购-已签订单
 */
import React from "react";
import { hashHistory } from 'react-router';
import Relay from "react-relay";
// import ListOrderMutation from "../mutation/ListOrderMutation";
import ListEnquiryOrderMutation from "../mutation/ListEnquiryOrderMutation";
import Check from '../Check';
import Util from "../../../util/Util"
import Pagination from "../Pagination";
import Reactkey from "../../../util/ReactKey";
import OrderPurch_Item from "./OrderPurch_Item";
import "./css/Order_OrderPurch_item.css";
import Modal_PayFor from "./Modal_PayFor";
import { Table,message,Menu, Dropdown, Icon } from 'antd';
import Modal_Supplement  from "./Modal_Supplement"
import DelOrderMutation from "../mutation/DelOrderMutation"
import BatchHint from "./BatchHint"
/*信息列表*/
export default class ListOrder extends React.Component{
    constructor(props){
        super(props);
        this.state={
            orders:[],
            totalresult:0,
            placeholder:'请输入企业名称进行搜索',
            loading:true,
        };
        this.enterpriseId = sessionStorage.getItem('enterpriseId');
        this.permissionId = sessionStorage.getItem('permissionId');
        this.uid = sessionStorage.getItem('uid');
        this.serviceType = sessionStorage.getItem('serviceType');
        this.odtail='1';
        this.ods='-1,0,1,2';
        this.goodtypeobj={'1':'成衣','2':'辅料','3':'面料','4':'印染','5':'纱线'}
        this.odsobj={'-1':'待创建',0:'待发布',1:'待接单',2:'待签订',3:'已签订',4:'交易完成'};
        this.oddstatus=["全部:1,2,3,4","已发布:1,2","已签订:3","已完成:4"];
        this.enid = sessionStorage.getItem('enterpriseId');

        this.order_purch_oid = '';
        this.order_purch_account = '';
        this.order_purch_status = '';
        this.order_purch_type = '';

    }
    componentWillMount(){
        this.queryorderlist(10,1);
    }
    componentDidMount(){

    }

    queryorderlist(pageSize,pageNum){
        let enName = this.refs.enName ? this.refs.enName.state.text : '';
        let orderType = '';
        if(this.serviceType ==1){
            orderType = '1,2,3'
        }else if(this.serviceType ==2){
            orderType = '2'
        }else if(this.serviceType ==3){
            orderType = '4,5'
        }else if(this.serviceType ==4){
            orderType = '4'
        }else if(this.serviceType ==5){
            orderType = '5'
        }else if(this.serviceType ==6){
            orderType = '1,2,3'
        }
        this.order_purch_oid = '';
        Relay.Store.commitUpdate(
            new ListEnquiryOrderMutation({
                pageSize: pageSize,
                pageNum: pageNum,
                status:this.ods,
                type:'2',
                enId:this.enid,
                enName:enName||'',
                searchType:2,
                orderType:orderType
            }),
            {
                onFailure: () => {
                    message.info('请求失败');
                    this.setState({
                        loading:false,
                    });
                },
                onSuccess: (response) => {
                    let errorCode = response.listEnquiryOrder.listEnquiryOrder.errorCode;
                    if(errorCode=='0'){
                        let orders = response.listEnquiryOrder.listEnquiryOrder.orders
                        let totalResult = response.listEnquiryOrder.listEnquiryOrder.totalResult
                        this.setState({
                            orders:orders,
                            totalresult:totalResult,
                            loading:false,
                        });
                    }else {
                        this.setState({
                            loading:false,
                        });
                        if (errorCode == 500){
                            message.error('服务器错误,请联系系统管理员');
                        }
                    }
                }
            }
        )
    }

    handleclick(){

    }

    check(){
        this.refs.check.setState({
            visible : true
        })
    }

    reloadList(){
        this.queryorderlist(10,1);
    }

    addDepartmenlist(){
        return this.state.orders.map((context,index)=>{
            let date = Util.dateFormat(context.createDate);
            let ods=this.odsobj[context.status];
            return (
                <OrderPurch_Item context={context} key = {Reactkey.key} index={index} _onChangeBoxCallBack = {this._onChangeBoxCallBack.bind(this)}
                                 ref={'order_item'+index} reloadList={this.reloadList.bind(this)}/>
            );
        });
    }

    _onChangeBoxCallBack(chooseindex,oid,account,check,status,type){
        if(check){
            this.order_purch_oid = oid;
            this.order_purch_account = account;
            this.order_purch_status = status;
            this.order_purch_type = type
        }else{
            this.order_purch_oid = '';
            this.order_purch_account = '';
            this.order_purch_status = '';
            this.order_purch_type = '';
        }
        this.state.orders.map((context,index)=>{
            if(chooseindex != index){
                this.refs['order_item'+index]._onChangeBoxFalse();
            }
        });
    }

    stroke(){

    }

    status(){
        return this.oArr.map((item,index)=>{
            return (
                <span style={{width:80,height:27,borderRadius:"8px",background:"#ccc",display:"block"}} onClick={this.stroke.bind(this)}>{item}</span>
            )
        })
    }

    createorder(){
        hashHistory.push('/createorder')
    }

    onSure(size,num){
        this.setState({
            loading:true,
        },this.queryorderlist(size,num))
    }

    /*确认框-点击确定*/
    BatchHintOk(type,value){
        switch (type){
            case "delete":
                Relay.Store.commitUpdate(
                    new DelOrderMutation({
                        orderId:value
                    }),
                    {
                        onFailure: () => {
                            message.info('请求失败');
                        },
                        onSuccess: (response) => {
                            let errorCode = response.delOrder.delOrder.errorCode;
                            let value = response.delOrder.delOrder.value;
                            if(errorCode=='0'){
                                let num = this.refs.pagination.state.text;
                                this.queryorderlist(10,num);
                                message.info('删除成功');
                            }else {
                                if (errorCode == 500){
                                    message.error('服务器错误,请联系系统管理员');
                                }else{
                                    message.error(value);
                                }
                            }
                        }
                    }
                );
                break;
            case "complete":

                break;
        }
    }
    render(){
        let { orders } = this.state;
        const columns = [
            {
                title: '订单编号',
                dataIndex: 'oid',
                key: 'oid',
                width: 260,
                render: (text, record) => {
                    return(
                            <span title={record.oid} className="order_orderpurch_item_from_td_oid">{record.oid}</span>
                        )
                },
            },
            {
                title: '商品类型',
                dataIndex: 'orderType',
                key: 'orderType',
                render:(text, record) =>{
                    return <span className="">{this.goodtypeobj[record.orderType]}</span>
                }
            },
            {
                title: '数量',
                dataIndex: 'orderGoodsNum',
                key: 'orderGoodsNum',
                width: 150,
                render:(text, record) =>{
                    return <span className="">{Number(record.orderGoodsNum).toFixed(3)}</span>
                }
            },
            {
                title: '剩余数量',
                dataIndex: 'remainOrderGoodsNum',
                key: 'remainOrderGoodsNum',
                width: 150,
                render:(text, record) =>{
                    return <span className="">{Number(record.orderGoodsNum-record.remainOrderGoodsNum).toFixed(3)}</span>
                }
            },
            {
                title: '订单金额（元）',
                dataIndex: 'account',
                key: 'account',
                render:(text, record) =>{
                    return <span className="">{record.account/100}</span>
                }
            },
            {
                title: '付款金额（元）',
                dataIndex: 'payAccount',
                key: 'payAccount',
                render:(text, record) =>{
                    return <span className="">{record.payAccount/100}</span>
                }
            },
            {
                title: '订单状态',
                dataIndex: 'status',
                key: 'status',
                render:(text, record) =>{
                    return <span className="">{this.odsobj[record.status]}</span>
                }
            },
            {
                title: '操作',
                dataIndex: 'operate',
                key: 'operate',
                width: 100,
                render:(text, record) =>{
                    const fun = {
                        jumpDetail:()=>{
                            hashHistory.push({pathname:'/OrderIndex/',state:{
                                'record':record,
                                "defaultActiveKey":1,
                            }})
                        },
                        jumpEdit:()=>{
                            let type = {
                                1:"createordergms",
                                2:"createorderraw",
                                3:"createordercloth",
                                4:"createorderprint",
                                5:"createorderyarn",
                            };
                            hashHistory.push({pathname:'/creatorderbystep/',state:{
                                'oid':record.oid,
                                "name":type[record.orderType],
                                "fromEdit":"edit",
                                'enquiryId':record.enquiryId
                            }});
                        },
                        jumpModify:()=>{
                            let type = {
                                1:"createordergms",
                                2:"createorderraw",
                                3:"createordercloth",
                                4:"createorderprint",
                                5:"createorderyarn",
                            };
                            hashHistory.push({pathname:'/creatorderbystep/',state:{
                                'oid':record.oid,
                                "name":type[record.orderType],
                                "fromEdit":"modify",
                                'enquiryId':record.enquiryId,
                            }});
                        },
                        jumpDelete:()=>{
                            let  message = "确定删除此订单吗?";
                            this.refs.batchHint.showWindow(true,message,"warning","delete",record.oid);
                            // debugger
                            /*Modal.confirm({
                                title: '确定删除此订单吗?',
                                content: '',
                                onOk() {
                                    // console.log('OK');
                                    Relay.Store.commitUpdate(
                                        new DelOrderMutation({
                                            orderId:record.oid
                                        }),
                                        {
                                            onFailure: () => {
                                                message.info('请求失败');
                                            },
                                            onSuccess: (response) => {
                                                let errorCode = response.delOrder.delOrder.errorCode;
                                                if(errorCode=='0'){
                                                    let num = _this.refs.pagination.state.text;
                                                   _this.queryorderlist(10,num);
                                                    message.info('删除成功');
                                                }
                                            }
                                        }
                                    )
                                },
                                onCancel() {
                                    // console.log('Cancel');
                                },
                            })*/
                        },
                        jumpPublish:()=>{
                            /*creatOrderByStep-412页*/
                            hashHistory.push({pathname:'/publishOrder/',state:{
                                'oid':record.oid,
                                'enterpriseId':this.enterpriseId,
                                'orderType':record.orderType,
                                'account':record.account,
                               /* 'entype':this.entype,*/
                                'ordertype_num':record.orderType,
                                'enquiryId':record.enquiryId
                            }});
                        },
                        jumpSign:()=>{
                            hashHistory.push({pathname:'/OrderIndex/',state:{
                                'record':record,
                                "defaultActiveKey":2,
                            }})
                        },
                    };

                    const menuItem = [
                        {key:"publish",iconType:"rocket",text:"发布",onClick:()=>{fun.jumpPublish();}},
                        {key:"receive",iconType:"printer",text:"接单",onClick:()=>{fun.jumpDetail();}},
                        {key:"sign",iconType:"inbox",text:"签订",onClick:()=>{fun.jumpSign();}},
                        {key:"edit",iconType:"edit",text:"编辑",onClick:()=>{fun.jumpEdit()}},
                        {key:"modify",iconType:"tool",text:"修改",onClick:()=>{fun.jumpModify()}},
                        {key:"delete",iconType:"delete",text:"删除",onClick:()=>{fun.jumpDelete()}},
                        {key:"detail",iconType:"file-text",text:"查看详情",onClick:()=>{fun.jumpDetail()}},
                    ];
                    const menu = (
                        <Menu
                            className="listOrder_purchase_dropDown_menu"
                        >
                            {
                                menuItem.map((v,i)=>{
                                    if(record.status == -1){
                                        {/*待创建*/}
                                        if(record.version == 1){//version=1->有历史订单 有历史订单不能删除
                                            if(v.key == "edit"||v.key == "delete"){
                                                return (
                                                    <Menu.Item key={v.key}>
                                                        <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                    </Menu.Item>
                                                )
                                            }
                                        }else {
                                            if(v.key == "edit"){
                                                return (
                                                    <Menu.Item key={v.key}>
                                                        <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                    </Menu.Item>
                                                )
                                            }
                                        }
                                    }else if(record.status == 0 ){
                                        {/*待发布*/}
                                        if(record.version == 1){//version不是1代表有历史订单
                                            if(v.key == "publish"||v.key == "edit"||v.key == "delete"){
                                                return (
                                                    <Menu.Item key={v.key}>
                                                        <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                    </Menu.Item>
                                                )
                                            }
                                        }else {
                                            if(v.key == "publish"||v.key == "edit"){
                                                return (
                                                    <Menu.Item key={v.key}>
                                                        <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                    </Menu.Item>
                                                )
                                            }
                                        }
                                    }else if(record.status == 1){
                                        {/*待接单-已发布*/}
                                        if(v.key == "detail"||v.key == "modify"){
                                            return (
                                                <Menu.Item key={v.key}>
                                                    <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                </Menu.Item>
                                            )
                                        }
                                    }else if(record.status == 2){
                                        {/*待签订-已接单*/}
                                        if(v.key == "sign"||v.key == "detail"||v.key == "modify"){
                                            return (
                                                <Menu.Item key={v.key}>
                                                    <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                </Menu.Item>
                                            )
                                        }
                                    }
                                })
                            }
                        </Menu>
                    );
                    return (
                        <Dropdown overlay={menu} placement="bottomLeft">
                            <Icon type="ellipsis" className="listOrder_purchase_dropDown_icon"/>
                        </Dropdown>
                    )
                }
            },
        ];
        return (
            <div className="order_box">
                <div style={{height:"300px",background:"#fff",margin:"20px"}}>
                    {/*修改-0602*/}
                    <Table
                        columns={columns}
                        dataSource={orders}
                        className="order_table"
                        pagination={false}
                        rowKey={record => record.oid}
                        // scroll={{ x: 1190 }}
                        loading={this.state.loading}
                    />
                    <Check ref={"check"}/>
                    <Pagination eachSize={10} dataSize={this.state.totalresult} onSure={this.onSure.bind(this)} ref={'pagination'}/>
                </div>
                <Modal_PayFor ref={'modal_payfor'} uid={this.uid}/>
                <Modal_Supplement ref={'modal_supplement'} uid={this.uid}/>
                <BatchHint ref={"batchHint"} _handleOk={this.BatchHintOk.bind(this)} />
            </div>

        )
    }
}
